package com.zbu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbu.reggie.common.CustomException;
import com.zbu.reggie.entity.Category;
import com.zbu.reggie.entity.Dish;
import com.zbu.reggie.entity.Setmeal;
import com.zbu.reggie.mapper.CategoryMapper;
import com.zbu.reggie.service.CategoryService;
import com.zbu.reggie.service.DishService;
import com.zbu.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    /*根据id删除分类 删除之前判断是否关联了菜品和套餐*/
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        //判断是否关联了菜品
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, id);
        int count = dishService.count(dishWrapper);
        if (count > 0) {
            //  关联则抛出一个异常
            throw new CustomException("当前分类关联了菜品，不能删除");
        }

        // 判断是否关联了套餐
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        int count1 = setmealService.count(setmealWrapper);
        if (count1 > 0) {
            //关联则抛出一个异常
            throw new CustomException("当前分类关联了套餐，不能删除");
        }
        //正常删除
        super.removeById(id);
    }
}
